<!--
 * @Author: Wangtao
 * @Date: 2020-09-21 09:55:09
 * @LastEditors: zhanwang
 * @LastEditTime: 2022-01-17 16:24:45
-->
<template>
  <commonDrawer
          :title="drawerData.type==='add'?'新建预览外呼任务':'更新预览外呼任务'"
          :drawer="drawer"
          size='870px'
          :appendToBody="true"
          @closeDraw="openOrCloseDrawer('close')"
          @cancelFun="drawer=false"
          @save="submitForm">
    <template slot="column">
     <el-form
            class="m7-form demo-ruleForm"
            :model="ruleForm"
            :rules="rules"
            ref="ruleFormRef"
            label-width="100px"
            :label-position="'top'"
          >
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="任务备注" prop="desc">
              <el-input type="textarea" v-model="ruleForm.remark"></el-input>
            </el-form-item>
            <!-- <el-form-item
              label="座席工号"
              prop="userList"
              :rules="[
                { required: !(ruleForm.userList.length > 0 || ruleForm.skillgroup.length > 0), message: '座席工号必填', trigger: 'change' }
              ]"
            >
              <m7Select
                v-if="drawerData.type==='add'"
                size="mini"
                v-model="ruleForm.userList"
                :placeholder="'请选择座席'"
                filterable
                :multiple="true"
                clearable
                :collapseTags="false"
                :options="userList"
                :defaultProps="{ label: 'agentNumber', value: '_id' }"
              >
              </m7Select>
              <selectEcho
               v-else
               :propValue="ruleForm.userList"
               :options="userList"
               :defaultProps="{ label: 'agentNumber', value: '_id' }"
              ></selectEcho>
            </el-form-item>
            <el-form-item
              label="技能组"
              prop="skillgroup"
              :rules="[
                { required: !(ruleForm.userList.length > 0 || ruleForm.skillgroup.length > 0), message: '技能组必填', trigger: 'change' }
              ]"
            >
              <m7Select
                v-if="drawerData.type==='add'"
                size="mini"
                v-model="ruleForm.skillgroup"
                :placeholder="'请选择技能组'"
                filterable
                :multiple="true"
                :collapseTags="false"
                clearable
                :options="queueList"
                :defaultProps="{ label: 'name', value: '_id' }"
                style="margin-bottom: 10px"
              >
              </m7Select>
              <selectEcho
               v-else
               :propValue="ruleForm.skillgroup"
               :options="queueList"
               :defaultProps="{ label: 'name', value: '_id' }"
              ></selectEcho>
            </el-form-item>
            <div class="warn-text"><span class="el-icon-info"></span>选择座席或技能组组后，取两者的座席合集，分配数据时将执行平均分配的原则</div> -->
          <el-form-item label="参与座席" prop="desc">
          <V7Transfer
            filterable
            leftcustomFilter
            :key="V7TransferIndex"
            buttonsClass="mybutton"
            size="mini"
            ref='V7Transfer'
            :props="{label: 'fullLabel', key: '_id'}"
            :custom-filter-method="filterMethod"
            :leftcustomFilterData='searchForm'
            :titles="['座席列表', '组内成员']"
            :button-texts="['删除', '添加']"
            filter-placeholder="请输入座席成员"
            v-model="uidsArr"
            :data="newAgentlist">
            <template v-slot:leftCustomFilter>
              <el-form style="padding: 5px; padding-top: 15px" :inline="true" label-position='top' size="mini" :model="formInline" class="demo-form-inline">
                <el-row >
                  <el-col :span="12">
                    <el-form-item >
                      <el-input v-model="searchForm.agent" clearable placeholder="请输入座席或工号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item >
                      <!-- <el-select v-model="searchForm.department" placeholder="活动区域">
                        <el-option label="区域一" value="shanghai"></el-option>
                        <el-option label="区域二" value="beijing"></el-option>
                      </el-select> -->
                      <el-cascader
                        v-model="searchForm.department"
                        collapse-tags
                        filterable
                        placeholder="请选择部门"
                        :props="{label: 'name', multiple: true, checkStrictly: true, value: '_id'}"
                        :options="schemaData">
                        </el-cascader>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </template>
          </V7Transfer>
          </el-form-item>
           <template v-if="drawerData.type!=='add'">
                  <el-form-item label="请选择数据处理规则" prop="distributionRules">
                    <span slot="label">
                      请选择数据处理规则
                    <el-tooltip class="item" effect="dark" placement="top">
                        <div slot="content">
                        只针对修改过坐席后生效，如果未修改过座席人员，则不会生效 <br>
                        将所选呼叫结果的数据从新分配：将之前所有座席的数据回收并且重新平均分配给调整后的所有座席 <br>
                        将删除座席的数据平均分配：将删除座席的所有数据平均分配给调整后的所有座席 <br>
                        </div>
                        <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                    </el-tooltip>
                    </span>
                    <el-select style="width: 100%" clearable v-model="ruleForm.distributionRules" placeholder="请选择">
                      <el-option label="将所选呼叫结果数据重新分配" :value="'0'"></el-option>
                      <el-option label="将删除座席的数据重新分配" :value="'1'"></el-option>
                    </el-select>
                      <!-- <el-radio @click.native.prevent="radioClick(0)" :label="0" v-model="ruleForm.distributionRules">将所选呼叫结果数据重新分配</el-radio> -->
                      <!-- <el-radio @click.native.prevent="radioClick(1)"  :label="1" v-model="ruleForm.distributionRules">将删除的数据重新分配</el-radio> -->
                  </el-form-item>
                  <el-form-item v-if="ruleForm.distributionRules==='0'" label="请选择再分配的数据类型" prop="redistributionDataType" :rules="[{required: true, message: '请选择', trigger: 'blur'}]">
                    <span slot="label">
                      请选择再分配的数据类型
                    <el-tooltip class="item" effect="dark" :content="`系统会将所选类型的数据全部回收，并且重新分配给所有的坐席`" placement="top">
                        <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                    </el-tooltip>
                    </span>
                     <el-checkbox-group v-model="ruleForm.redistributionDataType">
                      <el-checkbox label="UNDEAL">未呼叫</el-checkbox>
                      <el-checkbox label="DEALING">已接听</el-checkbox>
                      <el-checkbox label="NOT_DEAL">未接听</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <div v-else style="height: 100px"></div>
           </template>
          </el-form>
    </template>
  </commonDrawer>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import commonDrawer from '@/common/views/drawer/index.vue'
import { CommonModule } from '@/store/modules/common/index'
import selectEcho from '@components/select/selectEcho.vue'
import { commonAction, deepClone } from '@/utils/common'
import cloneDeep from 'lodash/cloneDeep'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
import V7Transfer from '@/components/V7transfer/index.vue'
interface DrawObj {
  type: string
  form: any
}
@Component({
  name: 'PriviewEditOrAdd',
  components: { commonDrawer, selectEcho, V7Transfer }
})
export default class PriviewEditOrAdd extends Vue {
  @Prop({
    default: () => {
      return {}
    }
  }) private drawerData!: DrawObj

  private $getCache: any
  private $store: any
  private $message: any
  private drawer: boolean = false
  private ruleForm = {
    name: '',
    remark: '',
    skillgroup: [],
    userList: [],
    _id: '',
    distributionRules: '',
    redistributionDataType: [],
    users: []
  }

  private restForm = cloneDeep(this.ruleForm)

  private rules = {
    name: [
      { required: true, message: '请输入活动名称', trigger: 'blur' },
      { min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur' }
    ]
  }

  get account () {
    return this.$store.state.common.session.account._id
  }

  public openOrCloseDrawer (data: any) {
    this.V7TransferIndex++
    this.uidsArr = []
    this.drawer = !this.drawer
    if (data === 'close') {
      return
    }
    const newData = Object.keys(data)
    if (newData.length > 0) { // 编辑
      Object.keys(this.ruleForm).forEach((key) => {
        if (key === 'userList') {
          // this.ruleForm[key] = this.getArrByObjArr(data.agent, 'agentId')
        } else {
          if (data[key]) {
            this.ruleForm[key] = data[key]
          }
          if (key === 'users') {
            this.uidsArr = this.ruleForm[key]
          }
        }
      })
    } else { // 新增
      this.ruleForm = cloneDeep(this.restForm)
    }
    this.$nextTick(() => {
      const self = (this as any)
      self.$refs.ruleFormRef.clearValidate()
    })
  }

  private beforeMount () {
    this.$getCache('/base/action/general/cache/query', ['previewDialoutAgentList'], true, true, true)
    this.getTreeData()
  }

  private getArrByObjArr (objArr: any, key: string) {
    const arr: any = []
    objArr.forEach((element: any) => {
      arr.push(element?.[key])
    })
    return arr
  }

  private submitForm () {
    if (!this.uidsArr.length) {
      this.$message.error('座席不可为空')
      return
    }
    (this.$refs as any).ruleFormRef.validate((valid) => {
      if (valid) {
        let tip = '创建成功！'
        let queryUrl = '/call/action/task/create'
        const agentList = this.getAgentList()
        let queryData: any = {
          name: this.ruleForm.name,
          remark: this.ruleForm.remark,
          // skillgroup: this.ruleForm.skillgroup,
          agent: this.uidsArr
        }
        if (this.drawerData.type === 'edit') {
          tip = '更新成功'
          queryUrl = '/call/action/task/update'
          queryData = {
            _id: this.ruleForm._id,
            remark: this.ruleForm.remark,
            name: this.ruleForm.name,
            distributionRules: this.ruleForm.distributionRules,
            redistributionDataType: this.ruleForm.redistributionDataType,
            agent: this.uidsArr,
            users: this.uidsArr
          }
        } else {
          queryData.account = this.account
        }
        const actionData = {
          url: queryUrl,
          method: 'POST',
          data: queryData
        }
        commonAction(actionData).then(resp => {
          if (resp && resp.success) {
            (this.$message as any)({ message: tip, type: 'success' })
            this.$emit('updateInfoSuccess', queryData)
            this.drawer = false
          }
        }).catch(err => { console.log(err) })
      } else {
        return false
      }
    })
  }

  private getAgentList () {
    const agentList: any = []
    this.ruleForm.userList.forEach((id) => {
      this.userList.forEach((item) => {
        if (item._id === id) {
          agentList.push({
            agentName: item.agentName,
            agentId: item._id,
            agentNumber: item.agentNumber
          })
          return true
        }
      })
    })
    return agentList
  }

  public get newAgentlist () {
    const list = deepClone(CommonModule.publicCache.previewDialoutAgentList)
    for (let i = 0; i < list.length; i++) {
      const element = list[i];
      element.fullLabel = `${element.agentName} [${element.agentNumber}]`
    }
    return list || []
  }

  public get userList (): any {
    return CommonModule.publicCache.previewDialoutAgentList
  }

  public get queueList () {
    return CommonModule.publicCache.queueList
  }

  // #region
  private uidsArr = []
  private agentList = []
  private V7TransferIndex = 0
  private searchForm = {
    agent: '',
    department: []
  }

  private schemaData = []
  private filterMethod (val, item) {
    const { agent, department } = this.searchForm
    return item?.fullLabel?.includes(agent) && getval(item?.departmentConfig?.departmentIdList || [], department)

    function getval (list1, list2) {
      let res = false
      if (list2.length === 0) {
        return true
      }
      if (list1.length === 0 && list2.length !== 0) {
        return res
      }
      for (let i = 0; i < list2.length; i++) {
        const element = list2[i][list2[i].length - 1]
        console.log(list1, 2233)
        if (list1.includes(element)) {
          res = true
        }
      }
      return res
    }
  }

  public radioClick (val) {
    if (this.ruleForm.distributionRules === val) {
      this.ruleForm.distributionRules = ''
    } else {
      this.ruleForm.distributionRules = val
    }
  }

  private async getTreeData () { // 查询组织架构数据
    const result: any = await CommonModule.getDepartmentTree()
    this.schemaData = result.tree || []
  }
  // #endregion
}
</script>

<style lang="stylus" scoped>
.page-header
  padding 21px 24px 21px
  box-shadow 0px 0px 4px 0px #E0E6F0
  width 100%
  display flex
  align-items center
  font-weight 600
  font-size 14px
  i
    color #C4CDD4
    margin-right 8px
    cursor pointer
.exit-content
  height 100%
  display flex
  flex-direction column
  justify-content space-between
.edit-form
  height calc(100% - 50px)
  overflow scroll
  padding 24px
  box-sizing border-box
  max-width 400px
.edit-oprate
  height 50px
  display flex
  align-items center
  justify-content flex-end
  padding 5px 24px 20px
  box-sizing border-box
.warn-text
  background $bgc-reminder
  padding 14px
  margin-bottom 20px
  border-radius 4px
  line-height 1.5
  .el-icon-info
    color $c-warn
    padding-right 6px
    font-size 14px
    vertical-align middle
/deep/.mybutton
  width 180px
  button
    width 120px
    margin 0
    &:first-child
      margin-bottom 10px
/deep/.left-panel
  width 300px
.tip-span
  color $icon-gray
  font-size 12px
  cursor pointer
</style>
